//
//  UIImage+extension.m
//  CodeFor异步线程切圆角-减少混合图层
//
//  Created by relax on 2017/11/7.
//  Copyright © 2017年 relax. All rights reserved.
//

#import "UIImage+extension.h"

@implementation UIImage (extension)

- (void)rl_cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor complectionBlock:(void(^)(UIImage *))complectionBlock {
    // 耗时操作放在异步线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 1. 获取图片画板
        UIGraphicsBeginImageContextWithOptions(size, YES, 0);

        // 2. 填充画板的底色
        [fillColor setFill];
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        UIRectFill(rect);

        // 3. 开始裁切。矩形圆形路径
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
        [path addClip];

        // 4. 在底色上画图
        [self drawInRect:rect];

        // 5. 从画板获取图片
        UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

        // 6. 关闭上下文
        UIGraphicsEndImageContext();

        // 7. 回到主线程，返回图片。
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complectionBlock) {
                complectionBlock(resultImage);
            }
        });
    });
}

@end
